<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑角色' : '新增角色' }}</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" :disabled="form.code === 'admin'" />
        </el-form-item>
        
        <el-form-item label="角色标识" prop="code">
          <el-input 
            v-model="form.code" 
            placeholder="请输入角色标识，例如：admin、editor" 
            :disabled="isEdit" 
          />
          <div class="form-tip">角色标识一旦创建不可修改，将用于前端权限判断</div>
        </el-form-item>
        
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入角色描述" 
            :disabled="form.code === 'admin'" 
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" :disabled="form.code === 'admin'">
            <el-radio :value="'enabled'">启用</el-radio>
            <el-radio :value="'disabled'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :disabled="form.code === 'admin' && isEdit">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { roleApi } from '@/api/permission'
import type { Role } from '@/types'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const form = reactive<Partial<Role>>({
  name: '',
  code: '',
  description: '',
  status: 'enabled'
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在2到20个字符之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 30, message: '角色标识长度在2到30个字符之间', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '角色标识必须以小写字母开头，只能包含小写字母、数字和下划线', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { max: 200, message: '角色描述最多200个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 获取角色详情
const getDetail = async (id: string) => {
  loading.value = true
  try {
    // 这里可以调用实际的API
    // const res = await roleApi.getDetail(id)
    // Object.assign(form, res.data)
    
    // 模拟数据
    setTimeout(() => {
      const roleData: Record<string, Role> = {
        '1': {
          id: '1',
          name: '超级管理员',
          code: 'admin',
          description: '拥有所有权限的超级管理员角色',
          status: 'enabled',
          createTime: '2023-01-01 00:00:00',
          updateTime: '2023-01-01 00:00:00'
        },
        '2': {
          id: '2',
          name: '内容管理员',
          code: 'content_manager',
          description: '负责管理平台内容，包括公告、帮助文档、轮播图等',
          status: 'enabled',
          createTime: '2023-02-15 10:30:00',
          updateTime: '2023-02-15 10:30:00'
        }
      }
      
      if (roleData[id]) {
        Object.assign(form, roleData[id])
      } else {
        ElMessage.error('角色不存在')
        router.push('/permission/role')
      }
      
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取角色详情失败:', error)
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 超级管理员不可编辑
      if (form.code === 'admin' && isEdit.value) {
        ElMessage.warning('超级管理员角色不可修改')
        return
      }
      
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await roleApi.update(route.params.id as string, form)
          ElMessage.success('更新成功')
        } else {
          // 新增
          // await roleApi.create(form)
          ElMessage.success('添加成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/permission/role')
      } catch (error) {
        console.error('保存角色失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 取消
const cancel = () => {
  router.push('/permission/role')
}

// 生命周期
onMounted(() => {
  // 如果是编辑模式，获取详情
  if (isEdit.value && route.params.id) {
    getDetail(route.params.id as string)
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 13px;
}
</style> 